package org.awenlice.playerdailyshop.gui;

import com.mojang.logging.LogUtils;
import net.minecraft.server.level.ServerPlayer;
import net.minecraft.world.entity.player.Player;
import net.minecraft.world.inventory.ChestMenu;
import net.minecraft.world.inventory.ClickType;
import net.minecraft.world.inventory.MenuType;
import net.minecraft.world.inventory.Slot;
import net.minecraft.world.item.ItemStack;
import net.minecraft.network.chat.Component;
import org.awenlice.playerdailyshop.coin.PlayerCoinSystem;
import org.awenlice.playerdailyshop.data.PlayerBuyShopData;
import org.awenlice.playerdailyshop.data.PlayerBuyShopDataManager;
import org.awenlice.playerdailyshop.data.PlayerShopData;
import org.awenlice.playerdailyshop.data.PlayerShopDataManager;
import org.awenlice.playerdailyshop.util.InventoryHelper;
import org.slf4j.Logger;

public class ShopMenu extends ChestMenu {
    private static final Logger LOGGER = LogUtils.getLogger();

    public ShopMenu(int windowId, net.minecraft.world.entity.player.Inventory playerInventory, net.minecraft.world.Container shopInventory) {
        super(MenuType.GENERIC_9x3, windowId, playerInventory, shopInventory, 3); // 3 表示 3 行
    }

    @Override
    public ItemStack quickMoveStack(Player player, int slotIndex) {return ItemStack.EMPTY;}

    @Override
    public void clicked(int slotIndex, int button, ClickType clickType, Player player) {
        // 拦截双击操作
        if (clickType == ClickType.PICKUP_ALL) { return;}

        if (slotIndex >= 0 && slotIndex < this.slots.size()) {
            Slot slot = this.slots.get(slotIndex);
            ItemStack stack = slot.getItem();

            // 检查是否是从商店容器中拿取物品
            if (slot.container != player.getInventory() && !stack.isEmpty()) {
                int price = stack.getOrCreateTag().getInt("price");
                // 检查玩家是否有足够的金币并扣除
                if (PlayerCoinSystem.hasEnoughCoins(player, price)) {
                    stack.removeTagKey("price");
                    stack.removeTagKey("weight");
                    // 检测背包是否满
                    InventoryHelper.addItemToPlayerInventory(player, stack);
                    // 将商店内的物品设置为空
                    slot.set(ItemStack.EMPTY);
                    // 更新 PlayerShopData 中的数据
                    if (player instanceof ServerPlayer) {
                        ServerPlayer serverPlayer = (ServerPlayer) player;
                        PlayerShopData shopData = PlayerShopDataManager.get(serverPlayer);
                        shopData.getShopItems().set(slotIndex, ItemStack.EMPTY); // 更新出售商店数据
                        shopData.setDirty(); // 标记数据为脏，需要保存
                    }
                } else {
                    player.displayClientMessage(Component.translatable("pds.hasNotMoney"), false);
                }
                return; // 拦截操作
            }
        }
        // 其他情况（如玩家背包内的操作）正常处理
        super.clicked(slotIndex, button, clickType, player);
    }

}